package JDBC.Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JDBCTemplate {

    public static void update(String sql,Object... params){
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            connection = JDBCUtil.getConnection();
            ps = connection.prepareStatement(sql);
            for(int i=0;i<params.length;i++){
                ps.setObject(i+1,params[i]);
            }
            ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(rs,ps,connection);
        }

    }

    public static <T> T query(String sql,IRowMapper<T> rsh,Object... params){
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try{
            connection = JDBCUtil.getConnection();
            ps = connection.prepareStatement(sql);
            for(int i=0;i<params.length;i++){
                ps.setObject(i+1,params[i]);
            }
            rs = ps.executeQuery();
            return rsh.mapping(rs);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(rs,ps,connection);
        }

        return null;
    }
}
